﻿using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace MediaController.Utils.UI
{
    public class ProgressCell : DataGridViewImageCell
    {
        protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle,
                                                    TypeConverter valueTypeConverter,
                                                    TypeConverter formattedValueTypeConverter,
                                                    DataGridViewDataErrorContexts context)
        {
            // Create bitmap.
            var bmp = new Bitmap(Size.Width, Size.Height);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                // Percentage.
                double percentage;
                double.TryParse(Value.ToString(), out percentage);
                string text = percentage + " %";
                // Get width and height of text.
                var f = new Font("Verdana", 10, FontStyle.Regular);
                var w = (int)g.MeasureString(text, f).Width;
                var h = (int)g.MeasureString(text, f).Height;
                // Draw pile.
                g.DrawRectangle(Pens.Black, 2, 2, Size.Width - 6, Size.Height - 6);
                g.FillRectangle(Brushes.Blue, 3, 3, (float)((Size.Width - 6) * percentage / 100), Size.Height - 7);
                var rect = new RectangleF(0, 0, bmp.Width, bmp.Height);
                var sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                g.DrawString(text, f, Brushes.Red, rect, sf);
            }
            return bmp;
        }
    }
}